package XishiBackend.services.web;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import XishiBackend.base.Constant;
import XishiBackend.models.entity.Dishes;
import XishiBackend.models.repository.DishesRepository;

@Service
@Transactional
public class WebDishesService {
    @Autowired
    private DishesRepository dR;
    
    public boolean save(Dishes d) {
        Dishes rd = dR.save(d);
        if(!rd.getName().equals(d.getName())) {
            return false;
        }
        if(rd.getTypeId() != d.getTypeId()) {
            return false;
        }
        if(!rd.getDescription().equals(d.getDescription())) {
            return false;
        }
        if(Float.compare(rd.getPrice(), d.getPrice()) != 0) {
            return false;
        }
        if(d.getSales() != d.getSales()) {
            return false;
        }
        if(rd.getRecommand() != d.getRecommand()) {
            return false;
        }
        if(Float.compare(rd.getDiscount(), d.getDiscount()) != 0) {
            return false;
        }
        return true;
    }
    
    public boolean delete(long dishesId) {
        if(!dR.exists(dishesId)) {
            return false;
        }
        dR.delete(dishesId);
        return true;
    }
    
    public boolean onShow(long dishesId) {
        Dishes d = dR.findOne(dishesId);
        if(d == null) {
            return false;
        }
        d.setOnShow(Constant.ON_SHOW);
        dR.save(d);
        return true;
    }
    
    public boolean offShow(long dishesId) {
        Dishes d = dR.findOne(dishesId);
        if(d == null) {
            return false;
        }
        d.setOnShow(Constant.OFF_SHOW);
        dR.save(d);
        return true;
    }
    
    public Dishes findOne(long dishesId) {
        return dR.findOne(dishesId);
    }
    
    public List<Dishes> findAll() {
        Iterator<Dishes> iter = dR.findAll().iterator();
        List<Dishes> list = new ArrayList<Dishes>();
        while(iter.hasNext()) {
            Dishes d = iter.next();
            list.add(d);
        }
        return list;
    }
}
